<?php
$id = null;
if(isset($_REQUEST['id']) && trim($_REQUEST['id']) != '') {
	$id = $_REQUEST['id'];
}
$isNewMode = false;
if ($id === null) {
	$isNewMode = true;
}
$product = null;

if(!$isNewMode) { // update mode
	$productDao = new Dao_ProductDAO();
	$product = $productDao->getProductObjById($id);
}

if ($product === null && !$isNewMode) {
	echo "Không tìm thấy sản phẩm";
	die();
} else if($product !== null && !$isNewMode) {
	// update product
} else {
  // new mode
	$product = new Model_Product(array());
	$product->setViewTimes(0);
	$product->setDeleteFlg(0);
}

$imgProdPath     = '../' . PICTURE_PROD_FOLDER . '/';
?>
<script type="text/javascript">
Ext.onReady(function(){

	var txtName = Ext.create('Ext.form.field.Text', {
					itemId 		: "txtName",
					id			: "txtName",
				    hideLabel 	: true,
				    width 		: 220,
				    height 		: 22,
				    allowBlank 	: false,
				    blankText 	: "Phải&nbsp;nhập&nbsp;tên&nbsp;sản&nbsp;phẩm",
				    renderTo 	: "txtNamePlace",
				    maxLength 	: 150,
				});

	var categorystr = Ext.create('Ext.data.Store', {
	    fields: ['id', 'name'],
	    proxy: {
            type: 'ajax',
            url : 'get/datacmbcategory.php',
            reader : {
                type: 'json',
                root: 'items',
            }
        },
	});
	var loadDone = false;
	// Create the combo box, attached to the states data store
	var cmbcate = Ext.create('Ext.form.ComboBox', {
	    fieldLabel	: ' ',
	    store		: categorystr,
	    queryMode	: 'local',
	    displayField: 'name',
	    valueField	: 'id',
	    hideLabel 	: true,
	    height 		: 22,
	    width  		: 120,
	    itemId 		: "cmbcate",
	    id			: "cmbcate",
	    allowBlank 	: false,
	    blankText 	: "Phải&nbsp;nhập&nbsp;loại&nbsp;sản&nbsp;phẩm",
	    editable 	: false,
	    renderTo	: "CmbcatePlace",
	    listeners: {
	        change: {
	            fn: function(field, newValue, oldValue) {
		            if (loadDone == false) {
						return;
		            }
		            console.debug("run..")
	            	proclssstr.load({
						params : {
							id : newValue
						},
						callback : function () {
							var cb = Ext.getCmp("cmbproclss");
							if (proclssstr.getCount() > 0) {
								cb.setValue(cb.getStore().getAt(0).get(cb.valueField));
							}
						}
		            });
		        }
	        }
	    }
	});


	var proclssstr = Ext.create('Ext.data.Store', {
	    fields: ['id', 'name'],
	    proxy: {
            type: 'ajax',
            url : 'get/datacmbproclss.php',
            reader : {
                type: 'json',
                root: 'items',
            }
        },
	});

	// Create the combo box, attached to the states data store
	var cmbproclss = Ext.create('Ext.form.ComboBox', {
	    fieldLabel: ' ',
	    store: proclssstr,
	    queryMode: 'local',
	    displayField: 'name',
	    valueField: 'id',
	    hideLabel : true,
	    height : 22,
	    width  : 120,
	    itemId : "cmbproclss",
	    id     : "cmbproclss",
	    allowBlank : false,
	    blankText  : "Phải&nbsp;nhập&nbsp;nhóm&nbsp;sản&nbsp;phẩm",
	    editable   : false,
	    renderTo   : "cmbproclssPlace"
	});

	var txtOrigin = Ext.create('Ext.form.field.Text', {
		itemId 		: "txtOrigin",
		id			: "txtOrigin",
	    hideLabel 	: true,
	    width 		: 220,
	    height 		: 22,
	    renderTo	: "txtOriginPlace",
	    //allowBlank 	: false,
	    blankText 	: "Phải&nbsp;nhập&nbsp;xuất&nbsp;xứ",
	    maxLength 	: 200,
	    enforceMaxLength : true
	});

	var txtProductYear = Ext.create('Ext.form.field.Number', {
		itemId 		: "txtProductYear",
		id			: "txtProductYear",
	    hideLabel 	: true,
	    width 		: 120,
	    height 		: 22,
	    value 	 	: 0,
	    minValue 	: 0,
	    //allowBlank 	: false,
	    blankText 	: "Phải&nbsp;nhập&nbsp;năm&nbsp;sản&nbsp;xuất",
	    renderTo	: "txtProductYearPlace"
	});

	var txtCapacity = Ext.create('Ext.form.field.Number', {
		itemId 		: "txtCapacity",
		id			: "txtCapacity",
	    hideLabel 	: true,
	    width 		: 120,
	    height 		: 22,
	    //allowBlank 	: false,
	    blankText 	: "Phải&nbsp;nhập&nbsp;dung&nbsp;tích",
	    value 		: 0,
	    minValue 	: 0,
	    step		: 10,
	    renderTo	: "txtCapacityPlace"
	});

	var txtLevel = Ext.create('Ext.form.field.Number', {
		itemId 		: "txtLevel",
		id			: "txtLevel",
	    hideLabel 	: true,
	    width 		: 120,
	    height 		: 22,
	    blankText 	: "Phải&nbsp;nhập&nbsp;nồng&nbsp;độ",
	    value 		: 0,
	    minValue 	: 0,
	    maxValue 	: 100,
	    renderTo	: "txtLevelPlace"
	});

	var txtPrice = Ext.create('Ext.form.field.Number', {
		itemId 		: "txtPrice",
		id			: "txtPrice",
	    hideLabel 	: true,
	    width 		: 120,
	    height 		: 22,
	    //allowBlank 	: false,
	    blankText 	: "Phải&nbsp;nhập&nbsp;giá&nbsp;hiện&nbsp;tại",
	    value 		: 0,
	    minValue 	: 0,
	    renderTo	: "txtPricePlace"
	});

	var txtOldPrice = Ext.create('Ext.form.field.Number', {
		itemId 		: "txtOldPrice",
		id			: "txtOldPrice",
	    hideLabel 	: true,
	    width 		: 120,
	    height 		: 22,
	    //allowBlank 	: false,
	    blankText 	: "Phải&nbsp;nhập&nbsp;giá&nbsp;trước&nbsp;khuyến&nbsp;mãi",
	    value 		: 0,
	    minValue 	: 0,
	    renderTo	: "txtOldPricePlace"
	});


	Ext.tip.QuickTipManager.init();  // enable tooltips
	var txtDetail = Ext.create('Ext.form.HtmlEditor', {
		itemId 		: "txtDetail",
		id			: "txtDetail",
	    hideLabel 	: true,
	    width		: 580,
	    height		: 250,
	    enableSourceEdit : true,
	    renderTo	: "txtDetailPlace"
	});

	var txtViewTimes = Ext.create('Ext.form.field.Number', {
		itemId 		: "txtViewTimes",
		id			: "txtViewTimes",
	    hideLabel 	: true,
	    width 		: 120,
	    height 		: 22,
	    allowBlank 	: false,
	    blankText 	: "Phải&nbsp;nhập&nbsp;số&nbsp;lần&nbsp;xem&nbsp;(ít&nbsp;nhất&nbsp;là&nbsp;0)",
	    value 		: 0,
	    minValue 	: 0,
	    renderTo	: "txtViewTimesPlace"
	});


	var states = Ext.create('Ext.data.Store', {
	    fields: ['value', 'dis'],
	    data : [
	        {"value":"0", "dis":"Đang dùng"},
	        {"value":"1", "dis":"Đã xóa"}
	    ]
	});

	// Create the combo box, attached to the states data store
	var cmbStatus = Ext.create('Ext.form.ComboBox', {
	    fieldLabel		: ' ',
	    store			: states,
	    queryMode		: 'local',
	    displayField	: 'dis',
	    valueField		: 'value',
	    hideLabel 		: true,
	    height 			: 22,
	    width  			: 120,
	    value 			: "0",
	    itemId 			: "cmbStatus",
	    id				: "cmbStatus",
	    editable 		: false,
	    renderTo		: "CmbStatusPlace"
	});

	// File image is normal

	var idProd = $('#id').val();
	var name = $('#name').val();
	var id_category = $('#id_category').val();
	var id_prodclass = $('#id_prodclass').val();
	var originPlace = $('#originPlace').val();
	var productYear = $('#productYear').val();

	var capacity = $('#capacity').val();
	var level = $('#level').val();
	var price = $('#price').val();

	var oldPrice = $('#oldPrice').val();
	//var detail = $('#detail').val();
	//detail = $("<div/>").html(detail).text();
	 //detail = jQuery('<div />').text(detail).html();
	var viewTimes = $('#viewTimes').val();
	var deleteFLg = $('#deleteFLg').val();


	var txtName 		= Ext.getCmp("txtName");
	var cmbcate 		= Ext.getCmp("cmbcate");
	var cmbproclss 		= Ext.getCmp("cmbproclss");
	var txtOrigin 		= Ext.getCmp("txtOrigin");
	var txtProductYear 	= Ext.getCmp("txtProductYear");

	var txtCapacity 	= Ext.getCmp("txtCapacity");
	var txtLevel 		= Ext.getCmp("txtLevel");
	var txtLevel 		= Ext.getCmp("txtPrice");
	var txtOldPrice 	= Ext.getCmp("txtOldPrice");
	var txtDetail 		= Ext.getCmp("txtDetail");

	var txtViewTimes 	= Ext.getCmp("txtViewTimes");
	var cmbStatus 		= Ext.getCmp("cmbStatus");

	txtName.setValue(name);

	categorystr.load( {
		callback : function() {
			cmbcate.setValue(id_category);
			cmbcate.clearInvalid();
			loadDone = true;
		}
	});

	proclssstr.load( {
		params : {
			id : id_category
		},
		callback : function() {
			cmbproclss.setValue(id_prodclass);
			cmbproclss.clearInvalid();
		}
	});

	txtOrigin.setValue(originPlace);
	txtProductYear.setValue(productYear);

	txtCapacity.setValue(capacity);
	txtLevel.setValue(level);
	txtPrice.setValue(price);
	txtOldPrice.setValue(oldPrice);

	//txtDetail.setValue(detail);
	txtViewTimes.setValue(viewTimes);

	cmbStatus.setValue(deleteFLg);

	Ext.Ajax.request ({
	    url: 'get/getdetailproduct.php' ,
	    disableCaching: false ,
	    params: {
	        id: idProd
	    },
	    success: function (res) {
	        // JSON is {name:val, type:val}
	        //console.log (Ext.JSON.decode(res.responseText).name);
	    	txtDetail.setValue(res.responseText);
	    } ,
	    failure: function () {
	        console.log ('error');
	    }
	});


});

function checkInput() {
	console.debug("check input");
	var el = Ext.getCmp("txtName");
	if (!el.isValid()) {
		showError("Phải nhập tên sản phẩm", el);
		return false;
	}

	el = Ext.getCmp("cmbcate");
	if (!el.isValid()) {
		showError("Phải chọn loại sản phẩm");
		return false;
	}

	el = Ext.getCmp("cmbproclss");
	if (!el.isValid()) {
		showError("Phải chọn nhóm sản phẩm");
		return false;
	}

	el = Ext.getCmp("txtPrice");
	if (!el.isValid()) {
		showError("Phải nhập giá sản phẩm");
		return false;
	}

	el = Ext.getCmp("txtViewTimes");
	if (!el.isValid()) {
		showError("Phải nhập số lần xem");
		return false;
	}

	return true;
}

function setDataToForm() {
	console.debug("setDataToForm");
	var name 		= Ext.getCmp("txtName").getValue();
	var id_category = Ext.getCmp("cmbcate").getValue();
	var id_prodclass = Ext.getCmp("cmbproclss").getValue();
	var originPlace = Ext.getCmp("txtOrigin").getValue();

	var productYear = Ext.getCmp("txtProductYear").getValue();
	var capacity 	= Ext.getCmp("txtCapacity").getValue();
	var level 		= Ext.getCmp("txtLevel").getValue();
	var price 		= Ext.getCmp("txtPrice").getValue();

	var oldPrice 	= Ext.getCmp("txtOldPrice").getValue();
	var detail 		= Ext.getCmp("txtDetail").getValue();
	var viewTimes 	= Ext.getCmp("txtViewTimes").getValue();
	var deleteFLg 	= Ext.getCmp("cmbStatus").getValue();


	$('#name').val(name);
	$('#id_category').val(id_category);
	$('#id_prodclass').val(id_prodclass);
	$('#originPlace').val(originPlace);
	$('#productYear').val(productYear);

	$('#capacity').val(capacity);
	$('#level').val(level);
	$('#price').val(price);
	$('#oldPrice').val(oldPrice);
	$('#detail').val(detail);
	$('#viewTimes').val(viewTimes);
	$('#deleteFLg').val(deleteFLg);
}

function submitForm() {
	console.debug("sumbitform");
	if(!checkInput()) {
		return;
	}

	setDataToForm();
	console.debug("form submit");
	$('#form1').submit();
}

function insertImage(image) {
	//var detailEl 	= Ext.getCmp("txtDetail");
	//detailEl.insertAtCursor( "<br /> aaa <br />" );
	//window.open("importImage.php", "dataitem", "toolbar=no,menubar=no,scrollbars=yes,width=400,height=600");
	var detailEl 	= Ext.getCmp("txtDetail");
	$width = $("#imageW").val();
	$height = $("#imageH").val();

	detailEl.insertAtCursor(  "<img src='"+image.src+"' width='"+$width+"' height='"+$height+"'> " );
	detailEl.focus(false,200);
}

function HandlePopupResult(result) {
    //alert("result of popup is: " + result);

    console.debug(resutl);
    var detailEl 	= Ext.getCmp("txtDetail");
	detailEl.insertAtCursor( "<img src='"+resutl+"'" );
}


</script>

<form action="process/processproduct.php" method="post" id="form1" enctype="multipart/form-data">
	<input type="hidden"  id="id" name="id" value="<?php echo $product->getId();?>">
	<input type="hidden" id="name" name="name" value="<?php echo $product->getName(); ?>">
	<input type="hidden" id="id_category" name="id_category" value="<?php echo $product->getIdCategory(); ?>">
	<input type="hidden" id="id_prodclass" name="id_prodclass" value="<?php echo $product->getIdProductClass(); ?>">
	<input type="hidden" id="originPlace" name="originPlace" value="<?php echo $product->getOrigin(); ?>">
	<input type="hidden" id="productYear" name="productYear" value="<?php echo $product->getYearOfManufacture(); ?>">
	<input type="hidden" id="capacity" name="capacity" value="<?php echo $product->getCapacity(); ?>">
	<input type="hidden" id="price" name="price" value="<?php echo $product->getPrice(); ?>">
	<input type="hidden" id="oldPrice" name="oldPrice" value="<?php echo $product->getOldPrice(); ?>">
	<input type="hidden" id="level" name="level" value="<?php echo $product->getLevel(); ?>">
	<input type="hidden" id="detail" name="detail" value="<?php /*echo $product->getDetail();*/  //echoEscapeStr($product->getDetail()); ?> ">
	<input type="hidden" id="viewTimes" name="viewTimes" value="<?php echo $product->getViewTimes(); ?>">
	<input type="hidden" id="deleteFLg" name="deleteFLg" value="<?php echo $product->getDeleteFlg(); ?>">
	<table class="table-list" id="tableForm" >

		<tr>
			<td colspan="2" class="header-edit">Thêm / chỉnh sửa Sản phẩm
			<?php if ($product !== null && !$isNewMode) {?>
				(cập nhật)
			<?php } else { ?>
				(thêm mới)
			<?php } ?>
			</td>
		</tr>
		<?php if ($product !== null && !$isNewMode) {?>
		<tr height="40px;">
			<td width="15%">Mã Sản phẩm</td>
			<td>
			<?php echo $product->getId(); ?>
		</td>
		</tr>
		<?php } ?>
		<tr height="50px;">
			<td width="15%">Tên sản phẩm</td>
			<td >
				<span id="txtNamePlace"></span>
				(Tối đa 100 ký tự)
			</td>
		</tr>
		<tr height="50px;">
			<td width="15%">Loại sản phẩm</td>
			<td >
				<span id="CmbcatePlace"></span>
			</td>
		</tr>

		<tr height="50px;">
			<td width="15%">Nhóm sản phẩm</td>
			<td>
				<span id="cmbproclssPlace"></span>
			</td>
		</tr>

		<tr height="50px;">
			<td width="15%">Xuất xứ</td>
			<td>
				<span id="txtOriginPlace"></span> (200 ký tự)
			</td>
		</tr>

		<tr height="50px;">
			<td width="15%">Năm sản xuất</td>
			<td>
				<span id="txtProductYearPlace"></span>
			</td>
		</tr>

		<tr height="50px;">
			<td width="15%">Dung tích</td>
			<td>
				<span id="txtCapacityPlace"></span>(ml)
			</td>
		</tr>

		<tr height="50px;">
			<td width="15%">Nồng độ</td>
			<td>
				<span id="txtLevelPlace"></span> (%)(tối thiểu 0% - tối đa 100%)
			</td>
		</tr>

		<tr height="50px;">
			<td width="15%">Giá (hiện tại)</td>
			<td>
				<span id="txtPricePlace"></span>
			</td>
		</tr>

		<tr height="50px;">
			<td width="15%">Giá trước khuyến mãi</td>
			<td>
				<span id="txtOldPricePlace"></span>
			</td>
		</tr>

		<tr height="50px;">
			<td width="15%">Chi tiết  </td>
			<td>
			<a href="javascript:insertImage();">chèn hình</a>(ngang : <input type="text" id="imageW" value="50" class="numberWH">px, cao : <input class="numberWH" type="text" id="imageH" value="50" >px)
			<div>
			<?php require_once 'framepage/listImage.php';?>
			</div>
			<br />
				<span id="txtDetailPlace"></span>
			</td>
		</tr>

		<tr height="50px;">
			<td width="15%">Số lượt xem</td>
			<td>
				<span id="txtViewTimesPlace"></span>
			</td>
		</tr>

		<tr height="50px;">
			<td width="15%">Số lượt xem</td>
			<td>
				<span id="CmbStatusPlace"></span>
			</td>
		</tr>

		<tr height="50px;">
			<td width="15%">File hình</td>
			<td>
				<img alt="" src="../<?php echo $product->getFullImagePath();?>" width="80" height="80"><br />
				<input type="file" name="imageFile">
			</td>
		</tr>


		<tr>
			<td colspan="2" style="text-align: right;">
			<!-- <input type="button" value="Xóa"> -->
			<input type="button" value="Lưu" onclick="submitForm();">
			<?php
				$url = getUrlAdmin('listproduct.php', null);
			?>
			<input type="button" value="quay lại"
				onclick="location.href='<?php echo $url;?>'"></td>
		</tr>
	</table>
</form>

